package com.example.demo.controller;

import com.example.demo.WebSocket.WebSocketServer;
import com.example.demo.pojo.*;
import com.example.demo.server.ConverStationServer;
import com.example.demo.server.UserMessageServer;
import com.example.demo.utils.TokenTool;
import com.example.demo.utils.Tool;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 创建会话的Controller , 用于 , 创建会话,  删除会话 , 转发消息 , 等等
 *
 * @author 刘二朋
 * @date 2020-12-05 14:04
 */
@RestController
@RequestMapping("/conversation")
@Tag(name = "会话管理", description = "创建会话 , 查询会话的信息 , 修改会话的信息 ,转发用户的消息")
@CrossOrigin(origins = "*")//解决跨域问题
public class ConverSationController {

    //    自动注入一个ConverStationServer对象
    @Autowired
    ConverStationServer converStationServer;

    @Autowired
    UserMessageServer userMessageServer;

    /**
     * 创建会话的接口 , 用于 , 创建会话,  使用WenSocket向对应的开客户端 , 发送一个保存会话的消息
     *
     * @param user    要进行操作的用户
     * @param request 当前登录的用户
     * @return 返回成功的响应
     */
    @PostMapping("/addconversation")
    @ResponseBody
    @Operation(summary = "创建会话",
            responses = {
                    @ApiResponse(
                            responseCode = "2000",
                            description = "先判断,数据 , 是否包含会话,  如果存在 , 则修改状态 , 如果不存在 , 则创建会话",
                            content = @Content(
                                    mediaType = "application/json",
                                    examples = @ExampleObject(description = "data数据为：", value = "{\n" +
                                            "  \"code\": 2000,\n" +
                                            "  \"message\": \"创建成功！\",\n" +
                                            "  \"data\": {\n" +
                                            "    \"user\": {\n" +
                                            "      \"id\": 13123456781,\n" +
                                            "    },\n" +
                                            "  }\n" +
                                            "}")
                            )),
                    @ApiResponse(responseCode = "2001", description = "创建会话失败")
            })
    public Message addConverSation(@RequestBody SigIn user, HttpServletRequest request) {
        //会话的id
        int converid;
//        获取当前用户的账号
        Message message = new Message();
        String tokenUserId = TokenTool.getTokenUserId(request);
        //        判断 , 这个 , 会话 , 是否存在 , 如果存在 , 则修改状态 , 如果不存在 , 则创建会话
        List<Conversation> selectfromto = converStationServer.selectfromto(tokenUserId, user.getId());
        if (selectfromto.isEmpty()) {
//            为空 , 不存在会话 ,创建会话
            Conversation conversation = new Conversation();
            conversation.setFromid(tokenUserId);
            conversation.setToid(user.getId());
            conversation.setState("1"); //1表示 , 打开状态
            Conversation conversation1 = converStationServer.addConversation(conversation);
            converid = conversation1.getId();
        } else {
            converid = selectfromto.get(0).getId();
//        不为空 , 则修改会话的状态
            int i = converStationServer.updataFromto(tokenUserId, user.getId());
            if (i <= 0) {
                System.out.println("会话状态 , 修改失败 , 请重新试");
            }
        }
        // 向客户端发送请求 , 保存一个会话列表
        String str = "{\"category\":\"conversation\",\"specific\":\"SIX\",\"id\":\"" + tokenUserId + "\",\"converid\":\"" + converid + "\"}";
        WebSocketServer.sendMessageToUser(user.getId(), str); //开始发送消息
        String str2 = "{\"category\":\"conversation\",\"specific\":\"SIX\",\"id\":\"" + user.getId() + "\",\"converid\":\"" + converid + "\"}";
        WebSocketServer.sendMessageToUser(tokenUserId, str2); //开始发送消息
        message.setSuccessMessage("添加成功");
        return message;
    }

    /**
     * 获取所有的会话 , 并通过会话 , 获取对应的聊天消息 , 把数据 ,进行封装 , 返回到对应的客户端
     *
     * @param request 当前登录的用户
     * @return 返回成功的响应
     */
    @GetMapping("/getConversations")
    @ResponseBody
    @Operation(summary = "获取当前用户的所有会话",
            responses = {
                    @ApiResponse(
                            responseCode = "2000",
                            description = "获取会话",
                            content = @Content(
                                    mediaType = "application/json",
                                    examples = @ExampleObject(description = "data数据为：", value = "{\n" +
                                            "  \"code\": 2000,\n" +
                                            "  \"message\": \"获取成功！\",\n" +
                                            "  \"data\": {\n" +
                                            "    \"Conversations\": {\n" +
                                            "      \"id\": 1,\n" +
                                            "      \"fromid\": 13123456781,\n" +
                                            "      \"toid\": 13123456785,\n" +
                                            "      \"message[\": 所有的聊天记录,]\n" +
                                            "    },\n" +
                                            "  }\n" +
                                            "}"
                                    )
                            )),
                    @ApiResponse(responseCode = "2001", description = "创建会话失败")
            })
    public Message getConversations(HttpServletRequest request) {
        Message message = new Message();
//        获取当前登录的用户的账号
        String tokenUserId = TokenTool.getTokenUserId(request);
//        通过用户的账号 ， 获取该账号的所有的会话
        List<Conversation> selectfrom = converStationServer.selectfrom(tokenUserId);
//        遍历用户的会话列表 , 通过会话列表的id , 来获取对应的所有的聊天消息(创建一个容器 , 来保存会话,  与对应的聊天消息)
        List<ConversationAndMessage> list = new ArrayList<>();
        selectfrom.forEach(sf -> {
//            通过会话的id , 来查询 , 会话的所有的聊天记录
            List<Usermessage> usermessages = userMessageServer.selectUserMessage(sf.getId() + "");
//            创建一个会话 , 消息对象 , 保存,用户的会话  , 和对应的消息
            ConversationAndMessage cam = new ConversationAndMessage();
            cam.setId(sf.getId());         //会话的编号
            cam.setFromid(sf.getFromid()); //fromid
            cam.setToid(sf.getToid());    //toid
            cam.setUsermessages(usermessages); //存放的聊天消息
            list.add(cam);
        });
        message.setSuccessMessage("会话 , 获取成功 ").put("conver", list);
        return message;
    }


    /**
     * 上传图片的接口
     *
     * @param file 要上传的图片 ,
     * @return 返回上传成功后图片的路径地址
     */
    @PostMapping("/uploadimage")
    @ResponseBody
    @Operation(summary = "用户上传图片的方法",
            description = "不需要token",
            responses = {
                    @ApiResponse(
                            responseCode = "2000",
                            description = "上传成功",
                            content = @Content(
                                    mediaType = "application/json",
                                    examples = @ExampleObject(description = "data数据为：", value = "{\n" +
                                            "  \"code\": 2000,\n" +
                                            "  \"message\": \"修改成功！\",\n" +
                                            "  \"data\": {\n" +
                                            "    \"user\": {\n" +
                                            "    },\n" +
                                            "  }\n" +
                                            "}")
                            )),
                    @ApiResponse(responseCode = "2001", description = "请求错误")
            })
    public String uploadimage(@RequestParam("alterimage") MultipartFile file) {
//        获取static 目录
        String filePath = ClassUtils.getDefaultClassLoader().getResource("static/").getPath();
        //在static目录下创建pmessage目录
        File home = new File(filePath + "pmessage");
        if (!home.exists()) {
            home.mkdirs();
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        // 获取上传文件的名称
        // 指定文件的新的名字 ,是当前时间 , 加上后缀名
        fileName = new Date().getTime() + suffixName;
        File dest = new File(home, fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String urlpath = Tool.getDomain() + "/pmessage/" + fileName;
        return urlpath;
    }

    /**
     * 上传视频的接口
     *
     * @param file 要上传的图片 ,
     * @return 返回上传成功后图片的路径地址
     */
    @PostMapping("/videoMessage")
    @ResponseBody
    @Operation(summary = "用户上传视频的方法",
            description = "不需要token",
            responses = {
                    @ApiResponse(
                            responseCode = "2000",
                            description = "上传成功",
                            content = @Content(
                                    mediaType = "application/json",
                                    examples = @ExampleObject(description = "data数据为：", value = "{\n" +
                                            "  \"code\": 2000,\n" +
                                            "  \"message\": \"上传成功！\",\n" +
                                            "  \"data\": {\n" +
                                            "    \"user\": {\n" +
                                            "    },\n" +
                                            "  }\n" +
                                            "}")
                            )),
                    @ApiResponse(responseCode = "2001", description = "上传错误")
            })
    public String videoMessage(@RequestParam("altervideo") MultipartFile file) {
//        获取static 目录
        String filePath = ClassUtils.getDefaultClassLoader().getResource("static/").getPath();
        //在static目录下创建 vmessage 目录
        File home = new File(filePath + "vmessage");
        if (!home.exists()) {
            home.mkdirs();
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        // 获取上传文件的名称
        // 指定文件的新的名字 ,是当前时间 , 加上后缀名
        fileName = new Date().getTime() + suffixName;
        File dest = new File(home, fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String urlpath = Tool.getDomain() + "/vmessage/" + fileName;
        return urlpath;
    }


}
